﻿Imports RunEnv
Imports System.Windows.Forms
Imports System.Data.SqlClient

Public Class frmUserRight
    Private Const CN_RightID As Integer = 0
    Private Const CN_FuncName As Integer = 1
    Private Const CN_RightView As Integer = 2
    Private Const CN_RightEdit As Integer = 3
    Private Const CN_RightCreate As Integer = 4
    Private Const CN_RightDelete As Integer = 5
    Private Const CN_RightAudit As Integer = 6
    Private Const CN_RightAuthorize As Integer = 7
    Private Const CN_IsAllowMana As Integer = 8

    Private Const CN_ColCount As Integer = 9


    Private Const ROOTGROUP As String = "RootGroup"
    Private Const ROOTUSER As String = "RootUser"
    Private mdtUsers As DataTable
    Private mdtUserGroup As DataTable
    Private mdtUserRight As DataTable
    Private mdtvUserRight As DataView
    Private mdtAdapter As SqlDataAdapter
    Private mblnIsEditState As Boolean

    Private mstrCurrentUserID As String

    Public Sub ShowOpen()
        Try
            InitUserRight()
            InitGridUI()
            SetEditState(False)
            InitUserGroup()
            InitSubSystem()
            InitDB()

            Me.ShowDialog()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub InitDB()
        Dim updateCommand As New SqlCommand
        mdtAdapter = New SqlDataAdapter()
        updateCommand.CommandText = "Update B_UserRight Set RightValue = @RightValue ,IsAllowMana = @IsAllowMana " _
            & " Where UserID = @UserID And RightID = @RightID"
        updateCommand.Connection = CRunEnv.DBConnection.sqlConnection
        updateCommand.Parameters.Add("@RightValue", SqlDbType.Int, 4, "RightValue")
        updateCommand.Parameters.Add("@IsAllowMana", SqlDbType.Bit, 1, "IsAllowMana")
        updateCommand.Parameters.Add("@UserID", SqlDbType.NVarChar, 50, "UserID")
        updateCommand.Parameters.Add("@RightID", SqlDbType.NVarChar, 50, "RightID")
        updateCommand.Parameters("@UserID").SourceVersion = DataRowVersion.Original
        updateCommand.Parameters("@RightID").SourceVersion = DataRowVersion.Original
        mdtAdapter.UpdateCommand = updateCommand
    End Sub

    Private Sub InitGridUI()
        With DataGridView1
            .Columns.Add(New DataGridViewTextBoxColumn)
            .Columns.Add(New DataGridViewTextBoxColumn)
            .Columns.Add(New DataGridViewCheckBoxColumn)
            .Columns.Add(New DataGridViewCheckBoxColumn)
            .Columns.Add(New DataGridViewCheckBoxColumn)
            .Columns.Add(New DataGridViewCheckBoxColumn)
            .Columns.Add(New DataGridViewCheckBoxColumn)
            .Columns.Add(New DataGridViewCheckBoxColumn)
            .Columns.Add(New DataGridViewCheckBoxColumn)

            .Columns(CN_RightID).HeaderText = "权限编码"
            .Columns(CN_RightID).ReadOnly = True
            .Columns(CN_FuncName).HeaderText = "权限名称"
            .Columns(CN_FuncName).ReadOnly = True
            .Columns(CN_RightView).HeaderText = "查看"
            .Columns(CN_RightView).Width = 40
            .Columns(CN_RightEdit).HeaderText = "编辑"
            .Columns(CN_RightEdit).Width = 40
            .Columns(CN_RightCreate).HeaderText = "新增"
            .Columns(CN_RightCreate).Width = 40
            .Columns(CN_RightDelete).HeaderText = "删除"
            .Columns(CN_RightDelete).Width = 40
            .Columns(CN_RightAudit).HeaderText = "审核"
            .Columns(CN_RightAudit).Width = 40
            .Columns(CN_RightAuthorize).HeaderText = "授权"
            .Columns(CN_RightAuthorize).Width = 40
            .Columns(CN_IsAllowMana).HeaderText = "管理"
            .Columns(CN_IsAllowMana).Width = 40
        End With
    End Sub

    Private Sub InitUserGroup()
        Dim sql As String
        sql = "Select * From B_User" _
            & " Where IsStop = 0" _
            & " Order By UserID"
        mdtUsers = CRunEnv.DBConnection.GetDataTable(sql)
        sql = " Select * From B_UserGroup Order By UserGroupID"
        mdtUserGroup = CRunEnv.DBConnection.GetDataTable(sql)
        Me.TreeView1.Nodes.Add(ROOTGROUP, "组")
        For Each dtRow As DataRow In mdtUserGroup.Rows
            Me.TreeView1.Nodes(ROOTGROUP).Nodes.Add(dtRow.Item("UserGroupID"), dtRow.Item("UserGroupID"))
        Next

        If mdtUsers.Rows.Count <= 0 Then Exit Sub
        Me.TreeView1.Nodes.Add(ROOTUSER, "用户")
        For Each dtRow As DataRow In mdtUsers.Rows
            Me.TreeView1.Nodes(ROOTUSER).Nodes.Add(dtRow.Item("UserID"), dtRow.Item("UserName")).Name = dtRow.Item("UserID")
        Next
        TreeView1.SelectedNode = TreeView1.Nodes(ROOTUSER).Nodes(0)
        TreeView1.HideSelection = False
        TreeView1.ExpandAll()
    End Sub

    Private Sub InitSubSystem()
        Dim sql As String
        Dim dt As DataTable
        sql = "Select * From B_URSubSystem Order By SortNumber"
        dt = CRunEnv.DBConnection.GetDataTable(sql)
        For Each dtRow As DataRow In dt.Rows
            ListView1.Items.Add(CStr(dtRow.Item("SubSystemID"))).SubItems.Add(dtRow.Item("SubSystem"))
        Next
        If ListView1.Items.Count > 0 Then
            ListView1.Items(0).Selected = True
        End If
    End Sub

    Private Sub InitUserRight()
        Dim sql As String
        sql = "Select B_UserRight.UserID,B_UserRight.RightID,B_UserRight.RightValue," _
            & " B_URSysFunc.SubSystemID,B_URSysFunc.SortNumber,B_URSysFunc.FuncName,B_URSysFunc.RightTemplate," _
            & " B_UserRight.IsAllowMana" _
            & " From B_UserRight" _
            & " Left Join B_User On B_User.UserID = B_UserRight.UserID" _
            & " right Join B_URSysFunc On B_URSysFunc.RightID = B_UserRight.RightID" _
            & " Order By SortNumber"

        mdtUserRight = CRunEnv.DBConnection.GetDataTable(sql)
        mdtvUserRight = mdtUserRight.DefaultView
    End Sub

    Private Sub InitGrid()
        If TreeView1.Nodes.Count <= 0 Then
            DataGridView1.RowCount = 0
            Exit Sub
        End If

        If TreeView1.SelectedNode Is Nothing Then
            DataGridView1.RowCount = 0
            Exit Sub
        End If

        If ListView1.SelectedItems.Count <= 0 Then
            DataGridView1.RowCount = 0
            Exit Sub
        End If

        Dim userID As String
        Dim subSystemID As String
        Dim sqlInManagerRightID As String
        sqlInManagerRightID = GetCurrentUserManagerRightID()
        If Len(sqlInManagerRightID) > 0 Then
            sqlInManagerRightID = " And RightID IN " & sqlInManagerRightID
        End If
        userID = TreeView1.SelectedNode.Name
        subSystemID = ListView1.SelectedItems(0).Text
        mdtvUserRight.RowFilter = "UserID ='" & userID & "' And SubSystemID='" & subSystemID & "'" & sqlInManagerRightID
        With DataGridView1
            .RowCount = mdtvUserRight.Count

            .Refresh()
        End With
    End Sub

    Private Sub ListView1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ListView1.SelectedIndexChanged
        InitGrid()
    End Sub

    Private Sub TreeView1_AfterSelect(sender As Object, e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
        SetColIsAllowManaEditState(mblnIsEditState)
        InitGrid()
    End Sub

    Private Function GetCurrentUserManagerRightID() As String
        Dim sql As String
        Dim sqlInUserGroup As String = ""
        Dim sqlInManagerRightID As String = ""
        Dim currentUser As CUser
        Dim userID As String
        Dim dt As DataTable
        Try
            currentUser = CRunEnv.CurrentUser
            userID = currentUser.UserID
            mstrCurrentUserID = userID
            sql = "Select UserID,UserGroupID From B_UserGroupMap" _
                & " Where UserID ='" & userID & "'"
            dt = CRunEnv.DBConnection.GetDataTable(sql)
            For Each dtRow As DataRow In dt.Rows
                If Len(sqlInUserGroup) = 0 Then
                    sqlInUserGroup = "'" & dtRow.Item("UserGroupID") & "'"
                Else
                    sqlInUserGroup += ",'" & dtRow.Item("UserGroupID") & "'"
                End If
            Next

            If Len(sqlInUserGroup) > 0 Then
                sqlInUserGroup = "(UserID ='" & userID & "'" & " Or UserID In (" & sqlInUserGroup & "))"
            Else
                sqlInUserGroup = "UserID ='" & userID & "'"
            End If

            sql = "Select distinct RightID" _
                & " From B_UserRight" _
                & " Where " _
                & sqlInUserGroup _
                & " And IsAllowMana <> 0"
            dt = CRunEnv.DBConnection.GetDataTable(sql)
            For Each dtRow As DataRow In dt.Rows
                If Len(sqlInManagerRightID) = 0 Then
                    sqlInManagerRightID = "'" & dtRow.Item("RightID") & "'"
                Else
                    sqlInManagerRightID += ",'" & dtRow.Item("RightID") & "'"
                End If
            Next
            Return "(" & sqlInManagerRightID & ")"
        Catch ex As Exception
            MsgBox("获取用户管理的权限失败！", MsgBoxStyle.Exclamation, "系统提示")
            Return ""
        End Try

    End Function

    Private Sub DataGridView1_CellPainting(sender As Object, e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
        If mdtvUserRight.Count <= 0 Then Exit Sub
        If e.RowIndex < 0 Or e.RowIndex >= mdtvUserRight.Count Then Exit Sub
        Try
            Dim rightValue As Integer = mdtvUserRight.Item(e.RowIndex).Item("RightValue")
            Dim rightTemplate As Integer = CInt(mdtvUserRight.Item(e.RowIndex).Item("RightTemplate"))
            Dim rightName As CRight.Right
            Select Case e.ColumnIndex
                Case CN_RightID

                Case CN_FuncName

                Case CN_RightView
                    rightName = CRight.Right.rightView
                Case CN_RightEdit
                    rightName = CRight.Right.rightEdit
                Case CN_RightCreate
                    rightName = CRight.Right.rightCreate
                Case CN_RightDelete
                    rightName = CRight.Right.rightDelete
                Case CN_RightAudit
                    rightName = CRight.Right.rightAudit
                Case CN_RightAuthorize
                    rightName = CRight.Right.rightAuthorize
                Case CN_IsAllowMana

            End Select

            If rightName = 0 Then Exit Sub
            If mblnIsEditState Then
                DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ReadOnly = GetIsReadOnly(rightTemplate, rightName)
            End If


            If GetIsReadOnly(rightTemplate, rightName) Then
                DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.BackColor = Drawing.Color.AliceBlue
            Else
                DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Style.BackColor = Drawing.Color.White
            End If
        Catch ex As Exception
            MsgBox("设置单元格背景失败," & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
        End Try
        
    End Sub

    Private Sub DataGridView1_CellValueNeeded(sender As Object, e As System.Windows.Forms.DataGridViewCellValueEventArgs) Handles DataGridView1.CellValueNeeded
        Try
            If mdtvUserRight.Count <= 0 Then Exit Sub
            Dim rightValue As Integer = mdtvUserRight.Item(e.RowIndex).Item("RightValue")
            Dim rightTemplate As Integer = CInt(mdtvUserRight.Item(e.RowIndex).Item("RightTemplate"))
            Select Case e.ColumnIndex
                Case CN_RightID
                    e.Value = mdtvUserRight.Item(e.RowIndex).Item("RightID")
                Case CN_FuncName
                    e.Value = mdtvUserRight.Item(e.RowIndex).Item("FuncName")
                Case CN_RightView
                    e.Value = GetRight(rightValue, CRight.Right.rightView)
                Case CN_RightEdit
                    e.Value = GetRight(rightValue, CRight.Right.rightEdit)
                Case CN_RightCreate
                    e.Value = GetRight(rightValue, CRight.Right.rightCreate)
                Case CN_RightDelete
                    e.Value = GetRight(rightValue, CRight.Right.rightDelete)
                Case CN_RightAudit
                    e.Value = GetRight(rightValue, CRight.Right.rightAudit)
                Case CN_RightAuthorize
                    e.Value = GetRight(rightValue, CRight.Right.rightAuthorize)
                Case CN_IsAllowMana
                    e.Value = mdtvUserRight.Item(e.RowIndex).Item("IsAllowMana")

            End Select

        Catch ex As Exception
            MsgBox(ex.Message & "DataGridView1_CellValueNeeded")
        End Try
    End Sub

    Private Sub DataGridView1_CellValuePushed(sender As Object, e As System.Windows.Forms.DataGridViewCellValueEventArgs) Handles DataGridView1.CellValuePushed
        Dim rightValue As Integer = mdtvUserRight.Item(e.RowIndex).Item("RightValue")
        Select Case e.ColumnIndex
            Case CN_RightView
                mdtvUserRight.Item(e.RowIndex).Item("RightValue") = _
                    SetRight(rightValue, CRight.Right.rightView, CBool(e.Value))
            Case CN_RightEdit
                mdtvUserRight.Item(e.RowIndex).Item("RightValue") = _
                   SetRight(rightValue, CRight.Right.rightEdit, CBool(e.Value))
            Case CN_RightCreate
                mdtvUserRight.Item(e.RowIndex).Item("RightValue") = _
                   SetRight(rightValue, CRight.Right.rightCreate, CBool(e.Value))
            Case CN_RightDelete
                mdtvUserRight.Item(e.RowIndex).Item("RightValue") = _
                   SetRight(rightValue, CRight.Right.rightDelete, CBool(e.Value))
            Case CN_RightAudit
                mdtvUserRight.Item(e.RowIndex).Item("RightValue") = _
                   SetRight(rightValue, CRight.Right.rightAudit, CBool(e.Value))
            Case CN_RightAuthorize
                mdtvUserRight.Item(e.RowIndex).Item("RightValue") = _
                   SetRight(rightValue, CRight.Right.rightAuthorize, CBool(e.Value))
            Case CN_IsAllowMana
                mdtvUserRight.Item(e.RowIndex).Item("IsAllowMana") = _
                   CBool(e.Value)
        End Select
    End Sub

    Private Function GetIsReadOnly(ByVal rightTemplate As Integer, ByVal rightName As CRight.Right) As Boolean
        Return Not ((rightTemplate And rightName) > 0)
    End Function

    Private Function GetRight(ByVal rightValue As Integer, ByVal rightName As CRight.Right) As Boolean
        Return (rightValue And rightName) > 0
    End Function

    Private Function SetRight(ByVal rightValue As Integer, ByVal rightName As CRight.Right, ByVal isChecked As Boolean) As Integer
        rightValue = rightValue Or rightName
        If Not isChecked Then
            rightValue -= rightName
        End If
        Return rightValue
    End Function

    Private Sub ToolStrip1_ItemClicked(sender As Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ToolStrip1.ItemClicked
        Select Case e.ClickedItem.Text
            Case "修改"
                Edit()
            Case "保存"
                Save()
            Case "关闭"
                Me.Close()
        End Select
    End Sub

    Private Sub SetEditState(ByVal isEditState As Boolean)
        DataGridView1.ReadOnly = Not isEditState
        SetColIsAllowManaEditState(isEditState)
        If isEditState Then
            mblnIsEditState = True
            DataGridView1.Refresh()
        Else
            mblnIsEditState = False
            DataGridView1.Refresh()
        End If
        Me.ToolStripButton1.Enabled = Not isEditState
        Me.ToolStripButton2.Enabled = isEditState
        Me.ToolStripButton3.Enabled = Not isEditState
        TreeView1.Enabled = Not isEditState
        ListView1.Enabled = Not isEditState
    End Sub

    Private Sub SetColIsAllowManaEditState(ByVal isEditState As Boolean)

        If isEditState Then
            If CType(CRunEnv.CurrentUser, CUser).UserID = TreeView1.SelectedNode.Name Then
                DataGridView1.Columns(CN_IsAllowMana).ReadOnly = True
            Else
                DataGridView1.Columns(CN_IsAllowMana).ReadOnly = False
            End If
        End If

    End Sub

    Private Sub Edit()
        SetEditState(True)
    End Sub

    Private Sub Save()
        Try
            DataGridView1.CurrentCell = Nothing
            mdtAdapter.Update(mdtUserRight)
            SetEditState(False)
        Catch ex As Exception
            MsgBox("保存失败，" & ex.Message, MsgBoxStyle.Exclamation, "系统提示")
        End Try
    End Sub
End Class